package main

import (
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"net/url"
	"strings"
)

var map0 = make(map[int64]string, 0)

func main() {
	router := gin.Default()
	i := int64(0)
	map0[i] = "http://www.baidu.com"
	router.GET("/*filePath", gateway("http://www.baidu.com", false))
	router.Run(":18055")
}

func gateway(targetUrl string, ssl bool) func(context *gin.Context) {
	url, _ := url.Parse(targetUrl)
	host := url.Host
	if ssl {
		targetUrl = "https://" + host
	} else {
		targetUrl = "http://" + host
	}

	replaceUrl := func(body io.Reader, contentType string, contentLength int64, response *http.Response) (io.Reader, int64) {

		if strings.HasPrefix(contentType, "text/") {
			builder := &strings.Builder{}
			io.Copy(builder, body)
			s := builder.String()
			all := strings.ReplaceAll(s, "http://"+host, "")
			all = strings.ReplaceAll(all, "https://"+host, "")
			all = strings.ReplaceAll(all, "//"+host, "")
			print(all)
			return strings.NewReader(all), int64(len([]byte(all)))
		} else {
			return body, contentLength
		}
	}
	return func(context *gin.Context) {
		uri := context.Request.RequestURI
		response, _ := http.Get(targetUrl + uri)
		contentType := response.Header.Get("Content-Type")
		reader, i := replaceUrl(response.Body, contentType, response.ContentLength, response)
		context.DataFromReader(200, i, contentType, reader, nil)
	}
}
